package servlet;

import Dao.DBUtil;
import Dao.UserDao;
import eneity.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.SQLException;

@WebServlet("/login")
public class loginServet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf8");
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        System.out.println("账号: "+username);
        System.out.println("密码: "+password);
        resp.setContentType("text/html;charset=utf8");
        User user = null;
        try {
            user = UserDao.getUserInfo(username,password);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        if (user == null){
            System.out.println("登录失败!");
            resp.getWriter().write("登录失败!");
            resp.sendRedirect("login.jsp");
        }else{
            System.out.println("登录成功!");
            HttpSession session = req.getSession(true);
            session.setAttribute("username",username);
            resp.sendRedirect("index.jsp");
        }
    }
}
